#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

#define DEVICE_NAME "/sys/devices/virtual/csdn_dev_class/csdn_dev"

int sysfs_node_write(int sysfs_fd, char *opt_data, int opt_len)
{
    int fd = openat(sysfs_fd, "csdn_sysfs_write", O_WRONLY);
    if (fd < 0) {
        printf("openat failed, %s\n", strerror(errno));
        return -1;
    }

    int write_len = write(fd, opt_data, opt_len);
    if (write_len != opt_len) {
        printf("write failed! write_len: %d\n", write_len);
    }

    close(fd);
    return 0;
}

int sysfs_node_read(int sysfs_fd)
{
    char result_data[1024] = {0};
    int result_data_len = 1024;

    int fd = openat(sysfs_fd, "csdn_sysfs_read", O_RDONLY);
    if (fd < 0) {
        printf("openat failed, %s\n", strerror(errno));
        return -1;
    }

    int read_len = read(fd, result_data, result_data_len);
    printf("read_len: %d, result_data: %s\n", read_len, result_data);

    close(fd);
    return 0;
}

int main(int argc, char const *argv[])
{
    int cmd = 0;

    int sysfs_fd = open(DEVICE_NAME, O_RDONLY);
    if (sysfs_fd < 0) {
        printf("open failed! error:%s\n", strerror(errno));
        return 0;
    }

    while (1) {
        printf("input> ");
        scanf("%d", &cmd);
        switch (cmd) {
            case 1:
                sysfs_node_write(sysfs_fd, "enable", strlen("enable"));
            break;

            case 2:
                sysfs_node_write(sysfs_fd, "disable", strlen("disable"));
            break;

            case 3:
                sysfs_node_read(sysfs_fd);
            break;
        }
    }

    close(sysfs_fd);
    return 0;
}
